package com.xzp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class HttpAspect {

    //使用org.slf4j
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

//    @Before("execution(public * com.xzp.controller.GirlController.girlList(..))") //拦截GirlController中的girlList方法，..表示任意参数
//    public void log(){
//        System.out.println("xxxx--log-----");
//    }

    //使用@Pointcut注解

    @Pointcut("execution(public * com.xzp.controller.GirlController.*(..))") //切点在Controller中的所有方法
    public void log(){

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){  //org.aspectj.lang
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest  request = attributes.getRequest();  //javax.servlet.http
        //记录HTTP请求
        //url
        logger.info("url={}",request.getRequestURL());

        //请求method
        logger.info("method={}",request.getMethod());

        //ip
        logger.info("ip={}",request.getRemoteAddr());

        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());

        //参数
        logger.info("args={}",joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter(){
//        System.out.println("do after ...");
        logger.info("do after ...");
    }

    /**
     * 获取方法返回的结果
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        if (object!=null)
        logger.info("response={}", object.toString());
    }

}
